﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;
using static System.Net.Mime.MediaTypeNames;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ConferenceNews")]
	public class ConferenceNewsController : BaseDbController
	{
		[Route("Index/{ConferenceId}")]
		public async Task<ActionResult> Index(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == conferenceId);

			ViewBag.ConferenceId = conferenceId;
			ViewBag.ConferenceName = conferenceMaster.ConferenceName;
			ViewBag.ControllerName = Resources.ConferenceNews;
			ViewBag.Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn;

			var model = new ConferenceNewsModel();
			model.ConferenceId = conferenceId;
			LoginUser.ConferenceFunctionIdList = Utility.GetConferenceFunctionIdList(conferenceId);
			return View(model);
		}

		public async Task<ActionResult> ShowMain(string id)
		{
			var data = await DbContext.NewsInfo.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);

			var model = new ConferenceNewsModel();
			model.Url = data.MainPic;
			return View(model);
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ConferenceNewsModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = DbContext.NewsInfo.AsNoTracking().Where(x => !string.IsNullOrEmpty(x.Status) && x.ConferenceId == model.ConferenceId);
			if (!string.IsNullOrWhiteSpace(model.SelNewsTitle) && model.SelNewsTitle != "")
			{
				sql = sql.Where(x => x.NewsTitle.Contains(model.SelNewsTitle));
			}
			int total = await sql.CountAsync();

			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.Sort).ThenByDescending(x => x.UpdateDate).ThenBy(x => x.NewsTitle).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				NewsTitle = x.NewsTitle,
				NewsListId = DbContext.NewsListInfo.AsNoTracking().FirstOrDefault(y => y.ID == x.NewsListId)?.NewsListName,
				Keyword = x.Keyword,
				SimplePic = x.SimplePic,
				MainPic = x.MainPic,
				ShowTime = x.ShowTime == null ? string.Empty :
						(Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
						x.ShowTime.Value.ToString("yyyy-MM-dd") :
						x.ShowTime.Value.ToString("MM/dd/yyyy")),
				Recommendation = x.Recommendation,
				MobileShow = x.MobileShow,
				Stick = x.Stick,
				Link = x.Link,
				ViewCount = x.ViewCount,
				Status = x.Status,
				Sort = x.Sort,
				Remark = x.Remark,
				Creator = x.Creator,
				CreateIP = x.CreateIP,
				CreateDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
					x.CreateDate.Value.ToString("yyyy-MM-dd") :
					x.CreateDate.Value.ToString("MM/dd/yyyy")
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetEditData(string id)
		{
			var data = await DbContext.NewsInfo.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);
			if (data != null)
			{
				var result = new
				{
					NewsTitle = data.NewsTitle,
					NewsListId = data.NewsListId,
					Keyword = data.Keyword,
					SimplePic = Path.GetFileName(data.SimplePic),
					MainPic = Path.GetFileName(data.MainPic),
					ShowTime = Utility.SetDate(data.ShowTime, Request.Cookies["_culture"].Value),
					Recommendation = data.Recommendation == true ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
					MobileShow = data.MobileShow == true ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
					Stick = data.Stick == true ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
					Link = data.Link,
					sort = data.Sort,
					status = data.Status,
					remark = data.Remark,
					MainText = data.MainText,
					Abstract = data.Abstract
				};

				return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[ValidateInput(false)]
		[Route("Create/{ConferenceId}")]
		public async Task<JsonResult> Create(ConferenceNewsModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.NewsInfo.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ConferenceId == model.ConferenceId &&
						x.NewsTitle == model.NewsTitle);

			if (result != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.Name)),
						JsonRequestBehavior.AllowGet);
			}
			
			string nickName = DbContext.ConferenceMaster.AsNoTracking().FirstOrDefault(x => x.ID == model.ConferenceId)?.ConferenceNickName;
			string folder = Path.Combine(ConstValues.ConferenceImg, nickName);
			string pfolder = Path.Combine(Server.MapPath(ConstValues.ConferenceImg), nickName);

			if (model.SimplePic != null)
			{
				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.SimplePic.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.SimplePic.FileName);
				model.SimplePicPath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.SimplePic.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
			}
			if (model.MainPic != null)
			{
				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.MainPic.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.MainPic.FileName);
				model.MainPicPath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.MainPic.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
			}

			var newslistName = DbContext.NewsListInfo.AsNoTracking().FirstOrDefault(x => x.ID == model.NewsListId)?.NewsListName;

			var newId = Utility.GetTableId(ConstValues.TableName.NewsInfo);

			var newsInfo = new NewsInfo
			{
				ID = newId,
				NewsTitle = model.NewsTitle?.Trim(),
				NewsListId = model.NewsListId,
				Keyword = model.Keyword?.Trim(),
				SimplePic = model.SimplePicPath?.Trim(),
				MainPic = model.MainPicPath?.Trim(),
				ShowTime = model.ShowTime,
				Recommendation = model.IsRecommend == ConstValues.GenericSelectionType.有 ? true : false,
				MobileShow = model.IsShowInMobile == ConstValues.GenericSelectionType.有 ? true : false,
				Stick = model.IsTop == ConstValues.GenericSelectionType.有 ? true : false,
				Link = !string.IsNullOrWhiteSpace(model.Link) ? model.Link.Trim() :
						newslistName != ConstValues.Slider && newslistName != ConstValues.Login ?
						ConstValues.SystemWeb + "/MeetingNewsInfo/Index/" + newId : string.Empty,
				MainText = model.NewsEssay == null ? string.Empty : model.NewsEssay.Trim(),
				Abstract = model.Abstract == null ? string.Empty : model.Abstract.Trim(),
				ViewCount = ConstValues.intZero,
				ConferenceId = model.ConferenceId,
				Status = model.Status,
				Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort,
				Remark = model.Remark?.Trim(),
				Creator = LoginUser.UserName,
				CreateIP = LoginUser.IP,
				CreateDate = DateTime.Now
			};
			DbContext.NewsInfo.Add(newsInfo);
			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit), JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[ValidateInput(false)]
		[Route("Modify/{ConferenceId}")]
		public async Task<JsonResult> Modify(ConferenceNewsModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var exist = await DbContext.NewsInfo.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID != model.Id &&
						x.ConferenceId == model.ConferenceId &&
						x.NewsTitle == model.NewsTitle);

			if (exist != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.NewsTitle)),
						JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.NewsInfo.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			string nickName = DbContext.ConferenceMaster.AsNoTracking().FirstOrDefault(x => x.ID == model.ConferenceId)?.ConferenceNickName;
			string folder = Path.Combine(ConstValues.ConferenceImg, nickName);
			string pfolder = Path.Combine(Server.MapPath(ConstValues.ConferenceImg), nickName);

			if (model.SimplePic != null)
			{
				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.SimplePic.FileName).Replace(".", "").ToUpper() +
						ConstValues.strHyphen + DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.SimplePic.FileName);
				model.SimplePicPath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.SimplePic.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
				result.SimplePic = model.SimplePicPath;
			}
			else if (string.IsNullOrEmpty(model.SimplePicPath))
			{
				result.SimplePic = string.Empty;
			}

			if (model.MainPic != null)
			{
				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.MainPic.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.MainPic.FileName);
				model.MainPicPath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.MainPic.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
				result.MainPic = model.MainPicPath;
			}
			else if (string.IsNullOrEmpty(model.MainPicPath))
			{
				result.MainPic = string.Empty;
			}

			result.NewsTitle = model.NewsTitle?.Trim();
			result.NewsListId = model.NewsListId;
			result.Keyword = model.Keyword?.Trim();
			result.ShowTime = model.ShowTime;
			result.Recommendation = model.IsRecommend == ConstValues.GenericSelectionType.有 ? true : false;
			result.MobileShow = model.IsShowInMobile == ConstValues.GenericSelectionType.有 ? true : false;
			result.Stick = model.IsTop == ConstValues.GenericSelectionType.有 ? true : false;

			var newslistName = DbContext.NewsListInfo.AsNoTracking().FirstOrDefault(x => x.ID == model.NewsListId)?.NewsListName;
			result.Link = !string.IsNullOrWhiteSpace(model.Link) ? model.Link.Trim() :
					newslistName != ConstValues.Slider && newslistName != ConstValues.Login ?
					ConstValues.SystemWeb + "/MeetingNewsInfo/Index/" + result.ID : string.Empty;
			result.Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort;
			result.Remark = model.Remark?.Trim();
			result.Status = model.Status;
			result.MainText = model.NewsEssay == null ? string.Empty : model.NewsEssay.Trim();
			result.Abstract = model.Abstract == null ? string.Empty : model.Abstract.Trim();
			result.Updater = LoginUser.UserName;
			result.UpdateDate = DateTime.Now;
			result.UpdateIP = LoginUser.IP;

			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit), JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Delete/{ConferenceId}")]
		public async Task<JsonResult> Delete(ConferenceNewsModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.NewsInfo.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				DbContext.NewsInfo.Remove(result);
				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[Route("ShowPic/{id}")]
		public async Task<ActionResult> ShowPic(string id)
		{
			var tran = await DbContext.NewsInfo.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);

			if (tran != null && !string.IsNullOrEmpty(tran.SimplePic))
			{
				return File(tran.SimplePic, Application.Octet, Path.GetFileName(tran.SimplePic));
			}
			else
			{
				return File("~/Images/ConferenceNoPic.png", Application.Octet, Path.GetFileName("~/Images/ConferenceNoPic.png"));
			}
		}

		public async Task<ActionResult> MainImg(string uploadUrl)
		{
			var tran = await DbContext.NewsInfo.AsNoTracking().FirstOrDefaultAsync(x => x.MainPic == uploadUrl);
			if (tran != null && !string.IsNullOrEmpty(tran.MainPic))
			{
				return File(tran.MainPic, Application.Octet, Path.GetFileName(tran.MainPic));
			}
			else
			{
				return File("~/Images/ConferenceNoPic.png", Application.Octet, Path.GetFileName("~/Images/ConferenceNoPic.png"));
			}
		}
	}
}